package cn.wolfcode.crm.web.controller;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class ExceptionHandlerControllerAdvice {
    private MappingJackson2JsonView jsonView = new MappingJackson2JsonView();

    @ExceptionHandler(UnauthorizedException.class) // 针对 UnauthorizedException 异常处理
    public ModelAndView HandleUnauthorizedException(HandlerMethod handlerMethod, Exception e) {
        return getModelAndView(e, handlerMethod, "common/nopermission");
    }

    @ExceptionHandler(Exception.class) // 针对其他异常处理
    public ModelAndView HandleException(HandlerMethod handlerMethod, Exception e) {
        return getModelAndView(e, handlerMethod, "common/error");
    }

    private ModelAndView getModelAndView(Exception e, HandlerMethod handlerMethod, String viewName) {
        ResponseBody responseBodyAnno = handlerMethod.getMethodAnnotation(ResponseBody.class);
        e.printStackTrace();
        ModelAndView mv;
        if (responseBodyAnno == null) { // 响应 HTML
            mv = new ModelAndView(viewName, "ex", e);

        } else { // 响应 JSON
            Map<String, Object> modelMap;
            modelMap = new HashMap<>();
            modelMap.put("success", false);
            modelMap.put("msg", "您没有此操作权限");
            mv = new ModelAndView(jsonView, modelMap);
        }
        return mv;
    }
}
